﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Text;
using MM.DBUtility;

namespace MobileManager
{
    public partial class CutMobile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurUser"] == null)
            {
                Response.Redirect("Login.aspx");
                return;
            }
            if (!IsPostBack)
            {
                inputDateFrom.Value = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");
                inputDateTo.Value = DateTime.Now.ToString("yyyy-MM-dd");

                GVDataBind();
            }
        }
        #region GV Bind
        private void GVDataBind()
        {
            string strSQL = "SELECT * FROM (SELECT A.Mobile,B.ProvinceName,A.CreateTime FROM T_CutMobile A WITH(NOLOCK) LEFT JOIN T_DH B WITH(NOLOCK) ON Left(A.Mobile,7)=B.DH WHERE 1=1 ";

            string strWhere = string.Empty;
            string strProvinceName = MM.DBUtility.BLSqlData.GetProvinceNamebyQuickName(txtProvince.TextValue.Trim()).Replace("省", "").Replace("市", "").Replace("壮族自治区", "").Replace("回族自治区", "").Replace("维吾尔自治区", "").Replace("特别行政区", "").Replace("自治区", "");
            if (!string.IsNullOrEmpty(strProvinceName))
                strWhere += string.Format(" AND B.ProvinceName=N'{0}'", strProvinceName);
            if (!string.IsNullOrEmpty(txtIMSI.Text.Trim()))
                strWhere += string.Format(" AND A.Mobile LIKE '%{0}%'", txtIMSI.Text.Trim());
            if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                strWhere += string.Format(" AND A.CreateTime BETWEEN '{0}' AND '{1}' ", inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));

            strSQL += strWhere + ") AS A";

            AspNetPager1.RecordCount = DbHelperSql.GetCount("SELECT COUNT(1) FROM (" + strSQL + ") AS B");

            string strOrder = " ORDER BY A.CreateTime DESC";

            if (AspNetPager1.CurrentPageIndex == 1)
                strSQL = string.Format(strSQL.Replace("SELECT *", "SELECT TOP {0} * "), AspNetPager1.PageSize) + strOrder;
            else
                strSQL = string.Format("SELECT TOP {0} * FROM ({1}) AS F WHERE rn BETWEEN {2} AND {3}", AspNetPager1.PageSize, strSQL.Replace("SELECT *", string.Format("SELECT *,row_number() over({0}) rn ", strOrder)), (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex * AspNetPager1.PageSize - 1);

            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            //ViewState["DataTemp"] = ds;
            lbCount.Text = "记录数：" + AspNetPager1.RecordCount;

        }
        protected void GVinfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //GVinfo.PageIndex = e.NewPageIndex;
            //GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
            //GVinfo.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            GVDataBind();
        }
        #endregion


        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                {
                    if (Convert.ToDateTime(inputDateFrom.Value) > Convert.ToDateTime(inputDateTo.Value))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "请求时间From必须小于等于To！");
                        return;
                    }
                }
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                string strSQL = "Delete FROM T_CutMobile Where 1=1";

                if (!string.IsNullOrEmpty(txtIMSI.Text.Trim()))
                    strSQL += string.Format(" AND Mobile LIKE '%{0}%'", txtIMSI.Text.Trim());
                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                    strSQL += string.Format(" AND CreateTime BETWEEN '{0}' AND '{1}' ", inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));

                DbHelperSql.ExecuteSql(strSQL);

                MM.Common.Common.PageStartAlert(this.Page, "删除成功！");

                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnADD_Click(object sender, EventArgs e)
        {
            try
            {
                string strIMSI = txtIMSI.Text.Trim();
                if (!string.IsNullOrEmpty(strIMSI))
                {
                    if (DbHelperSql.Exists(string.Format("SELECT 1 FROM T_CutMobile WITH(NOLOCK) WHERE Mobile='{0}'", strIMSI)))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "该手机号已经存在，请重新添加！");
                    }
                    else
                    {
                        DbHelperSql.ExecuteSql(string.Format("INSERT INTO T_CutMobile(Mobile) VALUES('{0}')", strIMSI));
                        MM.Common.Common.PageStartAlert(this.Page, "添加成功！");
                        GVDataBind();
                    }
                }
                else MM.Common.Common.PageStartAlert(this.Page, "手机号必须填写！");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnFU_Click(object sender, EventArgs e)
        {
            try
            {
                string strFilePath = fuMobile.FileName;
                if (!string.IsNullOrEmpty(strFilePath))
                {

                    if (System.IO.Path.GetExtension(strFilePath).ToLower().Equals(".txt"))
                    {
                        int FileLen = fuMobile.PostedFile.ContentLength;//获取上传文件的大小
                        byte[] input = new byte[FileLen];
                        System.IO.Stream UpLoadStream = fuMobile.PostedFile.InputStream;
                        UpLoadStream.Read(input, 0, FileLen);
                        UpLoadStream.Position = 0;
                        System.IO.StreamReader sr = new System.IO.StreamReader(UpLoadStream, System.Text.Encoding.Default);
                        StringBuilder sbSQL = new StringBuilder();

                        int intTemp = 0; bool bolTemp = false;
                        string strContent = sr.ReadLine();
                        while (!string.IsNullOrEmpty(strContent))
                        {
                            if (strContent.Trim().Length < 20)
                            {
                                sbSQL.Append(string.Format(" SELECT  '{0}' Mobile UNION ", strContent.Trim()));
                                intTemp++;
                                if (intTemp > 300)
                                {
                                    InsertData(sbSQL.ToString());
                                    sbSQL.Length = 0;
                                    intTemp = 0;
                                    bolTemp = true;
                                }
                            }
                            strContent = sr.ReadLine();
                        }

                        sr.Close();
                        UpLoadStream.Close();
                        UpLoadStream = null;
                        sr = null;

                        if (sbSQL.Length > 0)
                        {
                            InsertData(sbSQL.ToString());

                            MM.Common.Common.PageStartAlert(this.Page, "数据上传成功！");
                            GVDataBind();
                        }
                        else if (!bolTemp)
                            MM.Common.Common.PageStartAlert(this.Page, "无数据上传！");
                        else
                        {
                            MM.Common.Common.PageStartAlert(this.Page, "数据上传成功！");
                            GVDataBind();
                        }
                    }
                    else MM.Common.Common.PageStartAlert(this.Page, "只能上传txt文档！");
                }
                else
                {
                    MM.Common.Common.PageStartAlert(this.Page, "请选择文件！");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void InsertData(string strSQL)
        {
            strSQL = "INSERT INTO T_CutMobile(Mobile) SELECT * FROM (" + strSQL.Remove(strSQL.LastIndexOf("UNION")) + ") AS A WHERE A.Mobile NOT IN (SELECT Mobile FROM T_CutMobile)";
            DbHelperSql.ExecuteSql(strSQL);
        }
    }
}
